﻿using Microsoft.Extensions.Caching.Memory;

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace MicroDb.Querys
{
    class DBQueryable<T> : IOrderedQueryable<T>
    {

        public DBQueryable(IServiceProvider serviceProvider) : this(DBQueryProviderFactory.CreateQueryProvider(serviceProvider, typeof(T)))
        {

        }

        internal DBQueryable(IQueryProvider provider) : this(null, provider)
        {
        }

        internal DBQueryable(Expression expression, IQueryProvider provider)
        {
            this.Expression = expression ?? Expression.Constant(this);
            this.Provider = provider;
            this.ElementType = typeof(T);
        }
        public Type ElementType { get; }
        public Expression Expression { get; }
        public IQueryProvider Provider { get; }

        public IEnumerator<T> GetEnumerator()
        {
            return (Provider.Execute(Expression) as IEnumerable).Cast<T>().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return (Provider.Execute(Expression) as IEnumerable).GetEnumerator();
        }
    }

}
